﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data;
using System.Text;

public partial class MRP_CommonList : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        CheckCommonList("PaymentType", new string[] { "现金", "支票", "承兑"});

        CheckCommonList("PayPeriod", new string[] { "现款", "预付款", "月结", "月结30", "月结45", "月结60", "月结90" });


    }

    private static void CheckCommonList(string sListName, string[] sValues)
    {
        Database db = DatabaseFactory.CreateDatabase("MRPSqlServer");
        bool bNoRecorder = false;
        StringBuilder sbSQL = new StringBuilder();

        string sViewName=string.Format("View_{0}_List",sListName);

        string sSQL = string.Format("SELECT * FROM {0}", sViewName);
        IDataReader reader=null;
        //取得MaterialID
        try
        {
            using (reader = db.ExecuteReader(CommandType.Text, sSQL))
            {
                if (reader.Read())
                {
                    bNoRecorder = true;
                }
            }
        }
        catch (Exception ex)
        {
            db.ExecuteNonQuery(CommandType.Text, string.Format("CREATE VIEW [dbo].[View_{0}_List]AS SELECT CAST(ItemValue AS Int) AS ID, DisplayText FROM dbo.MRP_CommonLists WHERE(ListName = '{0}')",sListName));
            //reader = db.ExecuteReader(CommandType.Text, sSQL);
            using (reader = db.ExecuteReader(CommandType.Text, sSQL))
            {
                if (reader.Read())
                {
                    bNoRecorder = true;
                }
            }
        }

        if (bNoRecorder)
        {
            
            int i = 1;
            foreach (string sValue in sValues)
            {
                sbSQL.AppendFormat("INSERT INTO [MRP_CommonLists]([ListName],[ItemValue],[DisplayText] ,[ParentID],[ItemLevel],[SortOrder])VALUES('{0}',{1},'{2}',1,1,1);", sListName, i, sValue);
                
                i++;
            }
            if (sbSQL.Length > 0)
            {
                db.ExecuteNonQuery(CommandType.Text, sbSQL.ToString());
            }
        }
    }
}
